package com.gmail.blackdog1987.onedollar.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gmail.blackdog1987.onedollar.dao.SmsDao;
import com.gmail.blackdog1987.onedollar.entity.SmsEntity;
import com.gmail.blackdog1987.onedollar.service.SmsService;
import com.gmail.blackdog1987.onedollar.util.HttpInvoker;
import com.gmail.blackdog1987.onedollar.util.ParamSign;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

@Service("smsService")
public class SmsServiceImpl implements SmsService {
	private static String APP_ID = "145903640000247321";//应用ID------登录平台在应用设置可以找到
	private static String APP_SECRET = "a4b067520bf9217240eeae409e2d6de4";//应用secret-----登录平台在应用设置可以找到
	private static String ACCESS_TOKEN = "";//访问令牌AT-------CC模式，AC模式都可，推荐CC模式获取令牌
	private static final String GET_ACCESS_TOKEN_URL = "https://oauth.api.189.cn/emp/oauth2/v3/access_token?grant_type=client_credentials&&app_id="+APP_ID+"&app_secret="+APP_SECRET;
	@Autowired
	private SmsDao smsDao;

	/**
	 * 1 获取信任码token get提交
	 * 2自定义短信验证码下发 post提交
	 * @param userPhone 下发手机号
	 * @return
	 * @throws Exception
	 */
	public static String sendSms(String userPhone, String randcode) throws Exception {
		if(ACCESS_TOKEN==null||ACCESS_TOKEN.length()==0){
			String accessTokenStr = HttpInvoker.httpPost(GET_ACCESS_TOKEN_URL, null, null);
			JSONObject accessTokenJson = JSON.parseObject(accessTokenStr);
			ACCESS_TOKEN = (String) accessTokenJson.get("access_token");
		}

		Date date = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String timestamp = dateFormat.format(date);
//		System.err.println(timestamp);
		TreeMap<String, String> paramsMap = new TreeMap<String, String>();
		paramsMap.put("app_id", APP_ID);
		paramsMap.put("access_token", ACCESS_TOKEN);
		paramsMap.put("timestamp", timestamp);

		String getUrl = "http://api.189.cn/v2/dm/randcode/token?app_id=" + APP_ID
				+ "&access_token=" + ACCESS_TOKEN
				+ "&timestamp="+URLEncoder.encode(timestamp,"UTF-8")
				+ "&sign="+ ParamSign.value(paramsMap, APP_SECRET);
//		System.out.println(getUrl);
		String resJson = HttpInvoker.httpGet(getUrl,null);
//		System.err.println(resJson);
		Gson gson = new Gson();
		Map<String, String> map = gson.fromJson(resJson, new TypeToken<Map<String, String>>() {}.getType());
//		System.out.println(map.get("token"));//获取信任码


		//-----------------------------------------------------------
		TreeMap<String, String> paramsMap1 = new TreeMap<String, String>();
		paramsMap1.put("app_id", APP_ID);
		paramsMap1.put("access_token", ACCESS_TOKEN);
		paramsMap1.put("timestamp", timestamp);
		paramsMap1.put("token", map.get("token").toString());
		paramsMap1.put("randcode", randcode);
		paramsMap1.put("phone", userPhone);
		paramsMap1.put("exp_time", "2");

		String postUrl = "http://api.189.cn/v2/dm/randcode/sendSms";
//		System.out.println(map.get("token"));
		String postEntity = "app_id="+APP_ID
				+ "&access_token="+ACCESS_TOKEN
				+ "&token=" + map.get("token").toString()
				+ "&phone=" + userPhone
				+ "&randcode=" + randcode
				+ "&exp_time=2"
				+ "&timestamp="+ URLEncoder.encode(timestamp, "UTF-8")
				+ "&sign="+ParamSign.value(paramsMap1, APP_SECRET);
//		System.out.println(postEntity);
		String resJson1 = HttpInvoker.httpPost(postUrl,null,postEntity);
		Map<String,String> map2=gson.fromJson(resJson1, new TypeToken<Map<String, String>>() {
		}.getType());
//		System.out.println(resJson1);
		if(map2==null||map2.get("identifier")==null){
			return null;
		}
		String result=map2.get("identifier").toString();
//		System.out.println(resJson1);
		return result;
	}

	public void doSendSMS() {
		Map<String, Object> filter = new HashMap<String, Object>();
		Map<String, Object> sort = new HashMap<String, Object>();
		filter.put("status", 0);
		filter.put("falureCount<", 1);
		List<SmsEntity> smss = smsDao.find(filter, sort);
		for (SmsEntity sms : smss) {
			try {
				String result = sendSms(sms.getMobile(), sms.getContent());
				if (result==null){
					sms.setFalureCount(sms.getFalureCount()+1);
				}else{
					sms.setStatus(1);
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
		if(smss!=null&&smss.size()>0){
			smsDao.saveAll(smss);
		}
	}

}
